/*
 * @Description: 注册此服务 
 * @Autor: HuiSir<www.zuifengyun.com>
 * @Date: 2022-05-18 10:37:08
 * @LastEditTime: 2022-07-28 19:14:29
 */
import Micro from '../lib/Micro.js'
import useConfig from './useConfig.js'
import { print } from './useLog.js'
const { server, registerServer } = useConfig()

/**
 * 初始化
 * 访问注册中心，注册此服务
 */
function register(this: Micro) {
    if (!server) {
        throw new Error(`Config Error: 'server' is not defined! Please check the 'application.yml' configuration item.`)
    }

    if (!registerServer) {
        throw new Error(`Config Error: 'registerServer' is not defined! Please check the 'application.yml' configuration item.`)
    }

    print.info('正在连接注册中心...')

    this.client(registerServer, async (err) => {
        if (!err) {
            print.info('正在注册...')
            const { ok, msg } = await this.request({
                service: registerServer.name,
                path: '/save',
                data: { method: 'SYS', body: server }
            })
            if (ok === 1) {
                print.info(msg)
            } else {
                print.error('服务注册失败：' + msg)
            }
        } else {
            print.info('连接失败，30s后尝试重新连接...')
            const timer = setTimeout(() => {
                register.call(this)
                clearTimeout(timer)
            }, 30000)
        }
    })
}

export default register